import React, { useState, useEffect, useRef } from 'react';
import { io } from 'socket.io-client';
import './TcpMonitor.css';

const TcpMonitor = () => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [logs, setLogs] = useState([]);
  const [activeClients, setActiveClients] = useState({});
  const [isConnected, setIsConnected] = useState(false);
  const socketRef = useRef(null);
  const logsEndRef = useRef(null);

  useEffect(() => {
    // 创建Socket.IO连接
    const socket = io({
      path: '/socket.io',
      transports: ['websocket', 'polling'],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000
    });
    socketRef.current = socket;

    // 连接事件处理
    socket.on('connect', () => {
      console.log('TCP监控: WebSocket已连接到服务器');
      setIsConnected(true);
      addLog({
        type: 'system',
        message: 'WebSocket已连接到服务器',
        time: new Date().toISOString()
      });
    });

    socket.on('disconnect', () => {
      console.log('TCP监控: WebSocket已断开连接');
      setIsConnected(false);
      addLog({
        type: 'system',
        message: 'WebSocket已断开连接',
        time: new Date().toISOString()
      });
    });

    // TCP客户端连接事件
    socket.on('tcpClientConnected', (data) => {
      console.log('TCP监控: 收到客户端连接事件', data);
      addLog({
        type: 'connect',
        message: `TCP客户端已连接: ${data.address}`,
        time: data.time,
        data: data
      });
      
      // 更新活跃客户端列表
      setActiveClients(prev => ({
        ...prev,
        [data.address]: {
          address: data.address,
          connectedAt: data.time,
          username: null,
          lastActivity: data.time
        }
      }));
    });

    // TCP客户端数据事件
    socket.on('tcpClientData', (data) => {
      console.log('TCP监控: 收到客户端数据事件', data);
      addLog({
        type: 'data',
        message: `收到数据 [${data.address}]: ${data.data}`,
        time: data.time,
        data: data
      });
      
      // 尝试解析用户名
      let username = null;
      try {
        const parts = data.data.split('|');
        if (parts.length > 0) {
          username = parts[0];
        }
      } catch (err) {
        console.error('解析用户名失败:', err);
      }
      
      // 更新活跃客户端信息
      setActiveClients(prev => {
        const client = prev[data.address] || {};
        return {
          ...prev,
          [data.address]: {
            ...client,
            address: data.address,
            username: username || client.username,
            lastActivity: data.time,
            lastData: data.data
          }
        };
      });
    });

    // TCP客户端断开连接事件
    socket.on('tcpClientDisconnected', (data) => {
      addLog({
        type: 'disconnect',
        message: `TCP客户端已断开: ${data.address} ${data.username ? `(${data.username})` : ''}`,
        time: data.time,
        data: data
      });
      
      // 从活跃客户端列表中移除
      setActiveClients(prev => {
        const newClients = { ...prev };
        delete newClients[data.address];
        return newClients;
      });
    });

    // TCP客户端错误事件
    socket.on('tcpClientError', (data) => {
      addLog({
        type: 'error',
        message: `TCP客户端错误 [${data.address}]: ${data.error}`,
        time: data.time,
        data: data
      });
    });

    // 组件卸载时清理
    return () => {
      socket.disconnect();
    };
  }, []);

  // 添加日志并限制最大数量
  const addLog = (log) => {
    setLogs(prev => {
      const newLogs = [...prev, log];
      // 限制最多显示100条日志
      if (newLogs.length > 100) {
        return newLogs.slice(newLogs.length - 100);
      }
      return newLogs;
    });
  };

  // 自动滚动到底部
  useEffect(() => {
    if (logsEndRef.current && isExpanded) {
      logsEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [logs, isExpanded]);

  // 清除日志
  const clearLogs = () => {
    setLogs([]);
  };

  // 格式化时间
  const formatTime = (isoTime) => {
    try {
      const date = new Date(isoTime);
      return date.toLocaleTimeString('zh-CN', { 
        hour12: false,
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        fractionalSecondDigits: 3
      });
    } catch (e) {
      return isoTime;
    }
  };

  return (
    <div className={`tcp-monitor ${isExpanded ? 'expanded' : 'collapsed'}`}>
      <div className="monitor-header" onClick={() => setIsExpanded(!isExpanded)}>
        <h2>
          <span className={`status-indicator ${isConnected ? 'connected' : 'disconnected'}`}></span>
          TCP监控面板
          <span className="client-count">
            {Object.keys(activeClients).length} 个活跃连接
          </span>
        </h2>
        <span className="toggle-icon">{isExpanded ? '▼' : '▶'}</span>
      </div>
      
      {isExpanded && (
        <div className="monitor-content">
          <div className="monitor-toolbar">
            <button className="clear-button" onClick={clearLogs}>
              清除日志
            </button>
          </div>
          
          <div className="monitor-panels">
            <div className="clients-panel">
              <h3>活跃客户端 ({Object.keys(activeClients).length})</h3>
              <div className="clients-list">
                {Object.keys(activeClients).length === 0 ? (
                  <div className="no-clients">暂无活跃客户端</div>
                ) : (
                  Object.values(activeClients).map((client) => (
                    <div key={client.address} className="client-item">
                      <div className="client-address">{client.address}</div>
                      {client.username && (
                        <div className="client-username">用户名: {client.username}</div>
                      )}
                      <div className="client-time">
                        连接时间: {formatTime(client.connectedAt)}
                      </div>
                      <div className="client-activity">
                        最后活动: {formatTime(client.lastActivity)}
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>
            
            <div className="logs-panel">
              <h3>TCP通信日志</h3>
              <div className="logs-container">
                {logs.length === 0 ? (
                  <div className="no-logs">暂无日志记录</div>
                ) : (
                  logs.map((log, index) => (
                    <div key={index} className={`log-item ${log.type}`}>
                      <span className="log-time">[{formatTime(log.time)}]</span>
                      <span className="log-message">{log.message}</span>
                    </div>
                  ))
                )}
                <div ref={logsEndRef} />
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TcpMonitor; 